package cn.monkey.family.server.domain.shop.order;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.shop.item.Item;
import cn.monkey.family.data.shop.order.OrderDetail;
import cn.monkey.family.data.shop.order.OrderDetailQueryRequest;
import cn.monkey.family.server.domain.shop.item.BeforeItemDeleteEventListener;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class OrderItemBoundChecker implements BeforeItemDeleteEventListener {

    protected final OrderDetailRepository orderDetailRepository;

    public OrderItemBoundChecker(OrderDetailRepository orderDetailRepository) {
        this.orderDetailRepository = orderDetailRepository;
    }

    @Override
    public Result<Void> beforeItemDelete(RequestContext requestContext, Item item) {
        List<OrderDetail> orderDetails = orderDetailRepository.findAllByQueryRequest(OrderDetailQueryRequest.builder().skuId(item.getId()).build(), Sort.unsorted());
        if (CollectionUtils.isEmpty(orderDetails)) {
            return Results.ok();
        }
        return Results.fail("ITEM_HAS_BOUND_WITH_ORDER_DETAIL(S)");
    }
}
